package jannex.label;

import jannex.internal.BaseIterator;
import jannex.internal.Hashing;

import java.util.Arrays;
import java.util.Iterator;
import java.util.NoSuchElementException;

class ArrayLabelSet extends LabelSet {

    private final String[] labels;
    private final String[] table;

    ArrayLabelSet(String[] labels, String[] table) {
        this.labels = labels;
        this.table = table;
    }

    @Override
    public LabelList asList() {
        return new ArrayLabelList(labels);
    }

    @Override
    public String[] toArray() {
        return labels.clone();
    }

    @Override
    @SuppressWarnings({"unchecked", "SuspiciousSystemArraycopy"})
    public <S> S[] toArray(S[] s) {
        if (s.length < labels.length) {
            return (S[]) Arrays.copyOf(labels, labels.length, s.getClass());
        }
        System.arraycopy(labels, 0, s, 0, labels.length);
        if (s.length > labels.length) {
            s[labels.length] = null;
        }
        return s;
    }

    @Override
    public Iterator<String> iterator() {
        return new BaseIterator<String>() {
            int index;

            @Override
            public boolean hasNext() {
                return index < labels.length;
            }

            @Override
            public String next() {
                if (!hasNext()) {
                    throw new NoSuchElementException();
                }
                return labels[index++];
            }
        };
    }

    @Override
    public int size() {
        return labels.length;
    }

    @Override
    public boolean contains(Object target) {
        if (target == null || !(target instanceof String)) {
            return false;
        }
        String targetString = target.toString();
        for (int i = Hashing.smear(targetString.toLowerCase().hashCode()); ; i++) {
            String candidate = table[i & (table.length - 1)];
            if (candidate == null) {
                return false;
            }
            if (candidate.equalsIgnoreCase(targetString)) {
                return true;
            }
        }
    }
}
